from flask_restful import Resource
from flask_restful.reqparse import RequestParser
from flask import g
from comment.utils.decorators import login_required
from comment.modules.user import User
from comment.modules.Letter import Letter,Letter_Detail
from comment.modules import db
from financial.resources.letter.serializer import LetterPaginateSerializer

class Letter_Res(Resource):
    '''
    发送消息的资源类
    '''
    method_decorators = [login_required]

    def post(self):
        '''
        发送消息
        :return:
        '''
        rp = RequestParser()
        rp.add_argument('title',required=True)
        rp.add_argument('group')#群发消息时候  用户组
        rp.add_argument('rec_id')#单个用户发送时候 接受用户id
        rp.add_argument('content',required=True)

        args = rp.parse_args()
        title = args.get('title')

        group = args.get('group')
        rec_id = args.get('rec_id')
        content = args.get('content')


        #发送消息的用户id
        uid = g.user_id
        user = User.query.filter(User.id == uid).first()


        #群发消息  group 有三个值  2全体用户  0普通用户组 1管理员组
        if group == '0' and group == '1':#根据用户角色查询所有的接受用户
            rec_list = User.query.filter(User.role == int(group)).all()
        if group == '2':#群发消息给所有用户
            rec_list = User.query.all()
        #单个用户发送信息
        if rec_id:
            rec_user = User.query.filter(User.id == rec_id).first()
            if rec_user:
                rec_list = [rec_user]

        #把消息详情对象 插入到数据库
        new_letter_detail = Letter_Detail(title=title,detail = content)
        db.session.add(new_letter_detail)
        db.session.flush()
        for rec_user in rec_list:
            #给每个用户都发送消息
            letter = Letter(sendID=user.username,recID=rec_user.id,detail_id=new_letter_detail.id,state=0)
            db.session.add(letter)
        db.session.commit()
        return {'msg':'ok'}

    def get(self):
        '''
        当前用户 收到的消息列表(分页)
        :return:
        '''

        uid =g.user_id#当前登录的用户id
        user = User.query.filter(User.id == uid).first()
        rp = RequestParser()
        rp.add_argument('curPage',required=True) #访问的页号
        rp.add_argument('perPage',required=True)#每页显示数据的条数
        args = rp.parse_args()
        curPage = int(args.get('curPage'))
        perPage = int(args.get('perPage'))

        #letter_list 是pagination类型 包含分页的数据 同时在items属性中 包含消息列表数据
        letter_list = Letter.query.filter(Letter.recID == uid).paginate(curPage,perPage,error_out=False)

        dict_data = LetterPaginateSerializer(letter_list).to_dict()

        return {'msg':'ok','data':dict_data}